package com.zs.grain

import android.content.*
import android.content.pm.PackageManager
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Build.VERSION
import android.provider.Settings.Secure
import android.telephony.SubscriptionManager
import android.telephony.TelephonyManager
import android.util.Log
import androidx.core.app.ActivityCompat
import com.facebook.drawee.BuildConfig
import com.jeremyliao.liveeventbus.LiveEventBus
import com.tencent.bugly.beta.Beta
import com.xnkj1688.semplibrary.mvvm.BaseApplication
//import com.xnkj1688.semplibrary.ulti.AppInfo
import com.xnkj1688.semplibrary.ulti.AppUtil
import com.zs.grain.di.components.DaggerAppComponent
import com.zs.grain.service.*
import com.zs.grain.ui.MaintenanceActivity
import dagger.android.AndroidInjector
import dagger.android.DaggerApplication
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.schedulers.Schedulers
import java.io.File
import java.io.FileOutputStream
import java.lang.reflect.InvocationTargetException
import javax.inject.Inject

/**
 * Created by Wesley on 2017/7/6.
 */

class MyApplication : BaseApplication() {

    @Inject
    lateinit var mDataService: DataService
    @Inject
    lateinit var mDeviceService: DeviceService
    @Inject
    lateinit var mSignalRService: SignalRService
    @Inject
    lateinit var mSoundService: SoundService
    @Inject
    lateinit var mSyncService: SyncService
    @Inject
    lateinit var mTimerService: TimerService

    //private var mMessageReceiver: MessageReceiver? = null

    override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
        return DaggerAppComponent.builder().application(this).build()
    }

    override fun onCreate() {
        super.onCreate()
        Thread.currentThread().uncaughtExceptionHandler = ExceptionHandler(this)
        Thread.setDefaultUncaughtExceptionHandler(ExceptionHandler(this))
//        LeakCanary.install(this)
//        val rt = Runtime.getRuntime()
//        val maxMemory = rt.totalMemory() - rt.freeMemory()//rt.maxMemory()
//        Log.i("maxMemory:", java.lang.Long.toString(maxMemory / (1024 * 1024)))

        registerMessageReceiver()
        Single.just("")
            .observeOn(Schedulers.newThread())
            .subscribe({
                if (!BuildConfig.DEBUG) {
                    Beta.canShowUpgradeActs.add(MaintenanceActivity::class.java)
                    super.initBugly("9657ef35fb", mDataService.appChannel)
                }
                mDataService.insertLog("State:应用启动")
                copyFilesFromAssets(mDataService.craftPath)
                mDeviceService.init()

                var url = "http://" + mDataService.server
                val deviceId = AppUtil.getUniqueID(this)
                val verifyCode = mDataService.verifyCode
                mSignalRService.init(url, deviceId, verifyCode)
                mSyncService.init()

                mSoundService.init()
                mSoundService.init2()
                mTimerService.init()
                //LiveEventBus.get("SyncService.UpdateAppInfo").post("")

                copyFilesFromAssets(mDataService.imagesPath)
                copyFilesFromAssets(mDataService.adsPath)
            }, {
                it.printStackTrace()
            })

    }

    override fun onLowMemory() {
        super.onLowMemory()
        Log.d(TAG, "onLowMemory")
    }

    override fun onTrimMemory(level: Int) {
        super.onTrimMemory(level)
        Log.d(TAG, "onTrimMemory:" + level)
    }

    override fun onTerminate() {
        super.onTerminate()
        Log.d(TAG, "onTerminate")
    }


    private fun copyFilesFromAssets(path: String) {
        var dir = File(path)
        if (!dir.exists()) dir.mkdir()
        Observable.create<String>
        {
            val images = assets.list(dir.name)
            if (images == null) it.onComplete()
            for (item in images!!)
                it.onNext(item)
            it.onComplete()
        }.subscribe(
            {
                val file = File("$dir/$it")
                if (file.exists()) return@subscribe

                Log.d(TAG, it)
                val am = assets
                val input = am.open("${dir.name}/$it")
                val fos = FileOutputStream(file)
                val buf = ByteArray(10 * 1024)
                var size = input.read(buf, 0, 10240)
                while (size > 0) {
                    fos.write(buf, 0, size)
                    size = input.read(buf, 0, 10240)
                }
                input.close()
                fos.close()
            })
    }

    fun restartAndroid() {
        val componetName = ComponentName(
            "com.example.reboottest",
            "com.example.reboottest.MainActivity"
        );
        val intent = Intent();
        intent.setComponent(componetName);
        startActivity(intent);
    }

    private var mMessageReceiver: MessageReceiver? = null

    fun registerMessageReceiver() {
        mMessageReceiver = MessageReceiver()
        val filter = IntentFilter()
        filter.priority = IntentFilter.SYSTEM_HIGH_PRIORITY
//        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
//        filter.addAction(ACTION_USB_PERMISSION)
        this.registerReceiver(mMessageReceiver, filter)
    }

    inner class MessageReceiver : BroadcastReceiver() {

        override fun onReceive(context: Context, intent: Intent) {
            try {
                when (intent.action) {
//                    UsbManager.ACTION_USB_DEVICE_ATTACHED -> handleUsbAttached(context, intent)
//                    ACTION_USB_PERMISSION -> handleUsbPermession(context, intent)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    companion object {
        val TAG = "MyApplication"
        val ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION"
    }
}
